package com.smart_campus.activiti.controller;

import com.smart_campus.activiti.config.LeaveConfig;
import com.smart_campus.activiti.domain.Askforleave;
import com.smart_campus.activiti.service.AskforleaveService;
import com.smart_campus.activiti.vo.AskforleaveVo;
import com.smart_campus.sys.common.ActiveUser;
import com.smart_campus.sys.common.DataGridView;
import com.smart_campus.sys.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Task;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * @aytgor 陈鹏
 * @date 2020/6/28 14:57
 */
@RestController
@Slf4j
@RequestMapping("/leave")
public class LeaveController {
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private AskforleaveService askforleaveService;


    /**
     * 部署流程资源
     */
    @RequestMapping("/deployProcess")
    public void deployProcess() {
        Deployment deployment = processEngine.getRepositoryService()//获取流程定义和部署对象相关的Service
                .createDeployment()//创建部署对象
                .name("请假申请审核流程")//声明流程的名称
                .addClasspathResource("mapper/leave.png")//加载资源文件，一次只能加载一个文件
                .addClasspathResource("mapper/leave.xml")//
                .deploy();//完成部署
    }

    /**
     * 发送请求请假
     * @param askforleave
     * @return
     */
    @RequestMapping("startProcess")
    public LeaveConfig startProcess(Askforleave askforleave){
        try {
            User user=getUser();

            askforleave.setState(LeaveConfig.LEAVE_in_examination_and_approval);//单据状态 1、审批中 2、审批通过
            askforleave.setActivitiName(user.getUserId());
            //保存单据
            askforleaveService.insert(askforleave);
            System.out.println("返回的主键id"+askforleave.getActivitiId());


            //设置流程变量（单据和流程实例绑定的中间变量）
            Map vars = new HashMap();
            vars.put("activitiName",askforleave.getActivitiName());//用户名称
            vars.put("Days",askforleave.getDays());//天数
            //流程的名称
            String leavename = "leave";

            // 流程定义的Key
            String processDefinitionKey = leavename;
            Map<String, Object> variables = new HashMap<String, Object>();
            variables.put("DeanOfStudies",17);
            variables.put("President",18);
            variables.put("activitiName", askforleave.getActivitiName());//这里传入id为user1的用户
            variables.put("Days",askforleave.getDays());
            ProcessInstance processInstance = processEngine.getRuntimeService()// 与正在执行的流程实例和执行对象相关的Service
                    .startProcessInstanceByKey(processDefinitionKey, String.valueOf(askforleave.getActivitiId()),variables);// 使用流程定义的key启动流程实例，key对应leave.bpmn文件中id的属性

//        通过流程实例ID获取到当前正在实行的任务(填写申请也是一个任务)
            Task task =  taskService.createTaskQuery().processInstanceId(processInstance.getId()).orderByProcessInstanceId().desc().singleResult();
//        完成这个任务
            taskService.complete(task.getId(),vars);
            return LeaveConfig.LEAVE_ADD_YES;
        } catch (Exception e) {
            e.printStackTrace();
            return LeaveConfig.LEAVE_ADD_NO;
        }
    }

    /**
     * 返回用户的审批的列表
     * @return
     */
    @RequestMapping("ExamineAndApprove")
    public DataGridView ExamineAndApprove(){
        User user=getUser();//获取当前用户
        List<Integer> rid= askforleaveService.getUserRole(user);//获取用户的角色
        List<Task> list =new ArrayList<>();
        for (Integer id:rid) {
            System.out.println("角色id"+id);
            if (id==17){
                //根据用户名称查找办理人是我的任务(act_ru_task)
                list = taskService.createTaskQuery().taskAssignee(String.valueOf(id)).list();
            }else if(id==18){
                //根据用户名称查找办理人是我的任务(act_ru_task)
                list = taskService.createTaskQuery().taskAssignee(String.valueOf(id)).list();
            }
        }
        List<Askforleave> list1=new ArrayList<>();
        for (Task task:list) {
            //通过任务id查看任务实例
            Task task1=taskService.createTaskQuery().taskId(task.getId()).singleResult();
            //通过任务实例获取流程实例id
            String processInstans=task1.getProcessInstanceId();
            System.out.println("流程实例id"+processInstans);
            //通过流程实例id查询流程实例
            ProcessInstance result = runtimeService.createProcessInstanceQuery().processInstanceId(processInstans).singleResult();
            //通过流程实例获取businesskey的值
            String businessKey = result.getBusinessKey();
            //通过businesskey的值查询请假详情
            AskforleaveVo askforleaveVo= askforleaveService.getAskforleave(Integer.valueOf(businessKey));
            if (askforleaveVo!=null) {
                //设置任务id
                askforleaveVo.setProcessInstans(task.getId());
                //上传到前台
                list1.add(askforleaveVo);
            }
        }
        return new DataGridView(list1);
    }


    /**
     * 获取当前用户的方法
     * @return
     */
    public User getUser(){
        Subject subject = SecurityUtils.getSubject();
        ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
        User user = activeUser.getUser();
        //上面的方法是获取登入的用户
        return user;
    }


    /**
     * 停止任务
     * @param ids
     * @return
     */
    @RequestMapping("DeletelEAVE")
    public LeaveConfig DeletelEAVE(Integer[] ids){
        try {
            for (Integer id:ids) {
                System.out.println(id);
                askforleaveService.deleteByPrimaryKey(id);
            }
            return LeaveConfig.YES;
        } catch (Exception e) {
            e.printStackTrace();
            return LeaveConfig.NO;
        }
    }

    /**
     * 查询我的请假
     * @return
     */
    @RequestMapping("LookMylEAVE")
    public DataGridView LookMylEAVE(AskforleaveVo askforleave){
        User u=getUser();
        askforleave.setActivitiName(u.getUserId());
        return askforleaveService.LookMylEAVE(askforleave);
    }


    @RequestMapping("ApprovalTask")
    public LeaveConfig ApprovalTask(Integer ids,String pids,String type){
        try {
            System.out.println("请假id"+ids);
            System.out.println("流程id"+pids);
            System.out.println("选择的处理"+type);
            //通过任务id查看任务实例
            Task task1=taskService.createTaskQuery().taskId(pids).singleResult();
            //通过任务实例获取流程实例id
            String processInstans=task1.getProcessInstanceId();

            //完成任务
            this.taskService.complete(pids);
            //判断流程是否结束
            ProcessInstanceQuery processInstanceQuery=this.runtimeService.createProcessInstanceQuery().processInstanceId(processInstans);

            Askforleave askforleave=new Askforleave();
            askforleave.setActivitiId(ids);
            if("no".equals(type)){
                askforleave.setState(LeaveConfig.LEAVE_Approval_to_complete_No);
            }else if("yes".equals(type)){
                askforleave.setState(LeaveConfig.LEAVE_Approval_to_complete_Yes);
            }
            askforleaveService.updateByPrimaryKeySelective(askforleave);

            return LeaveConfig.YES;
        } catch (Exception e) {
            e.printStackTrace();
            return LeaveConfig.YES;
        }
    }
}
